<template>
  <view class="order-list-container">
    <!-- Tab切换区域 -->
    <view class="tab-section">
      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === 'physiotherapy' }"
          @click="switchTab('physiotherapy')"
        >
          <text class="tab-text">{{ $t('order_list.physiotherapy_prescription') }}</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ 'active': activeTab === 'chinese_medicine' }"
          @click="switchTab('chinese_medicine')"
        >
          <text class="tab-text">{{ $t('order_list.chinese_medicine_prescription') }}</text>
        </view>
      </view>
    </view>

    <!-- 理疗处方内容 -->
    <view v-if="activeTab === 'physiotherapy'" class="tab-content">
      <!-- 搜索条件区域 -->
      <view class="search-section">
      <view class="search-form">
        <!-- 时间范围选择 -->
        <view class="form-item">
          <view class="date-range">
            <picker mode="date" :value="searchForm.start" @change="onstartChange">
              <view class="date-picker">
                <text>{{ searchForm.start || $t('order_list.startDate') }}</text>
              </view>
            </picker>
            <text class="separator">{{$t('order_list.to')}}</text>
            <picker mode="date" :value="searchForm.end" @change="onendChange">
              <view class="date-picker">
                <text>{{ searchForm.end || $t('order_list.endDate') }}</text>
              </view>
            </picker>
          </view>
        </view>

        <!-- 搜索按钮 -->
        <view class="search-buttons">
          <button class="search-btn" @click="handleSearch">{{$t('order_list.search')}}</button>
          <button class="reset-btn" @click="handleReset">{{$t('order_list.reset')}}</button>
        </view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-section">

      <!-- 订单列表 -->
      <view class="order-list">
        <view v-for="(item, index) in orderList" :key="item.id || index" class="order-item" @click="handleOrderClick(item)">

          <view class="order-content">
            <view class="user-info">
              <text class="username">{{ item.patient_info.username || $t('order_list.unknownUser') }}</text>
              <text class="phone">{{ item.patient_info.email || 'N/A' }}</text>
            </view>

            <view class="order-details">
              <view class="product-list">
                <view v-for="(product, index) in item.good_info" :key="product.id || index" class="product-item">
                  <text class="product-name">{{ product.name || 'N/A' }}</text>
                  <text class="product-price">$ {{ product.price || '0.00' }}</text>
                </view>
              </view>
              <!-- <view class="total-section">
                <text class="total-label">总计：</text>
                <text class="amount">$ {{ getTotalPrice(item.good_info) }}</text>
              </view> -->
            </view>

            <view class="order-time">
              <text class="create-time">{{$t('order_list.createTime')}}{{ formatDate(item.create_datetime) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !loading" class="empty-state">
        <text class="empty-text">{{$t('order_list.noData')}}</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">{{$t('order_list.loading')}}</text>
      </view>
    </view>

      <!-- 加载更多提示 -->
      <view v-if="orderList.length > 0" class="load-more-section">
        <view v-if="loading" class="loading-more">
          <text class="loading-text">{{$t('common.loading')}}</text>
        </view>
        <view v-else-if="hasMore" class="load-more-tip">
          <text class="tip-text">{{$t('order_list.loadMore')}}</text>
        </view>
        <view v-else class="no-more">
          <text class="no-more-text">{{$t('order_list.noMoreData')}}</text>
        </view>
      </view>
    </view>

    <!-- 中药处方内容 -->
    <view v-if="activeTab === 'chinese_medicine'" class="tab-content">
      <!-- 搜索条件区域（中药处方） -->
      <view class="search-section">
        <view class="search-form">
          <!-- 时间范围选择 -->
          <view class="form-item">
            <view class="date-range">
              <picker mode="date" :value="cmSearchForm.start" @change="onCmStartChange">
                <view class="date-picker">
                  <text>{{ cmSearchForm.start || $t('order_list.startDate') }}</text>
                </view>
              </picker>
              <text class="separator">{{$t('order_list.to')}}</text>
              <picker mode="date" :value="cmSearchForm.end" @change="onCmEndChange">
                <view class="date-picker">
                  <text>{{ cmSearchForm.end || $t('order_list.endDate') }}</text>
                </view>
              </picker>
            </view>
          </view>

          <!-- 搜索按钮 -->
          <view class="search-buttons">
            <button class="search-btn" @click="handleCmSearch">{{$t('order_list.search')}}</button>
            <button class="reset-btn" @click="handleCmReset">{{$t('order_list.reset')}}</button>
          </view>
        </view>
      </view>

      <view class="list-section">
        <view class="order-list">
          <view 
            v-for="(item, index) in cmList" 
            :key="item.id || index" 
            class="order-item"
            @click="handleCmClick(item)"
          >
            <view class="order-content">
              <view class="user-info">
                <text class="username">{{ getCmPatientName(item) }}</text>
              </view>

              <view class="order-details">
                <view class="product-list">
                  <view class="product-item">
                    <text class="product-name">{{ $t('order_list.createTime') }}{{ item.create_datetime || '-' }}</text>
                  </view>
                  <view class="product-item">
                    <text class="product-name">{{ $t('order_list.diagnosis') }}：{{ getCmDiagnosis(item) }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="cmList.length === 0 && !cmLoading" class="empty-state">
          <text class="empty-text">{{$t('order_list.noData')}}</text>
        </view>

        <!-- 加载状态 -->
        <view v-if="cmLoading" class="loading-state">
          <text class="loading-text">{{$t('order_list.loading')}}</text>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <view v-if="cmList.length > 0" class="load-more-section">
        <view v-if="cmLoading" class="loading-more">
          <text class="loading-text">{{$t('common.loading')}}</text>
        </view>
        <view v-else-if="cmHasMore" class="load-more-tip">
          <text class="tip-text">{{$t('order_list.loadMore')}}</text>
        </view>
        <view v-else class="no-more">
          <text class="no-more-text">{{$t('order_list.noMoreData')}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderList } from '@/api/order.js'
import { getTreatmentRecordChineseMedicineList } from '@/api/medical.js'
import { formatDate } from '@/utils/date.js'

export default {
  name: 'OrderList',
  data() {
    return {
      // Tab状态
      activeTab: 'physiotherapy',

      // 搜索表单
      searchForm: {
        start: '',
        end: '',
        username: ''
      },

      // 列表数据
      orderList: [],
      loading: false,

      // 中药处方列表数据
      cmList: [],
      cmLoading: false,

      // 中药处方分页参数
      cmPage: 1,
      cmPageSize: 10,
      cmTotal: 0,
      cmHasMore: true,

      // 中药处方搜索表单
      cmSearchForm: {
        start: '',
        end: ''
      },

      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 0,
      hasMore: true,

      // 排序参数
      sortBy: 'createTime',
      sortOrder: 'desc'
    }
  },

  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize)
    }
  },

  onLoad() {
    this.loadOrderList()
  },

  onPullDownRefresh() {
    if (this.activeTab === 'chinese_medicine') {
      this.refreshChineseMedicineList()
    } else {
      this.refreshList()
    }
  },

  onReachBottom() {
    if (this.activeTab === 'chinese_medicine') {
      if (this.cmHasMore && !this.cmLoading) {
        this.loadMoreChineseMedicine()
      }
    } else {
      if (this.hasMore && !this.loading) {
        this.loadMore()
      }
    }
  },

  methods: {
    // Tab切换
    switchTab(tab) {
      this.activeTab = tab
      // 切换tab时重置搜索条件和列表数据
      if (tab === 'physiotherapy') {
        this.refreshList()
      } else if (tab === 'chinese_medicine') {
        // 懒加载：首次切换时加载
        if (this.cmList.length === 0) {
          this.refreshChineseMedicineList()
        }
      }
    },

    // 加载订单列表
    async loadOrderList() {
      if (this.loading) return

      this.loading = true
      try {
        const cleanedSearchForm = Object.fromEntries(
          Object.entries(this.searchForm).filter(([_, v]) => v !== '')
        )
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...cleanedSearchForm
        }

        const response = await getOrderList(params)

        if (response.code === 200 || response.success) {
          const newList = response.result.items
          this.orderList = newList
          this.total = response.data?.total || 0

          // 判断是否还有更多数据
          this.hasMore = newList.length === this.pageSize
        } else {
          uni.showToast({
            title: response.message || this.t('order_list.loadingListErr'),
            icon: 'none'
          })
        }
      } catch (error) {
        console.error(this.t('order_list.loadingListErr'), error)
        uni.showToast({
          title: this.t('order_list.error'),
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    // 中药处方：获取患者姓名
    getCmPatientName(item) {
      const lastName = item?.patient_info?.last_name || ''
      const firstName = item?.patient_info?.first_name || ''
      const name = `${lastName}${firstName}`.trim()
      return name || this.$t('order_list.unknownUser')
    },

    // 中药处方：获取诊断或辨证
    getCmDiagnosis(item) {
      const diagnosis = (item?.details?.diagnosis || '').trim()
      const dialectic = (item?.details?.dialectic || '').trim()
      return diagnosis || dialectic || '-'
    },

    // 中药处方：加载列表（覆盖式）
    async loadChineseMedicineList() {
      if (this.cmLoading) return
      this.cmLoading = true
      try {
        const cleanedCmSearchForm = Object.fromEntries(
          Object.entries(this.cmSearchForm).filter(([_, v]) => v !== '')
        )
        const params = {
          page: this.cmPage,
          pageSize: this.cmPageSize,
          ...cleanedCmSearchForm
        }
        const response = await getTreatmentRecordChineseMedicineList(params)
        if (response.code === 200 || response.success) {
          const newList = response.result?.items || []
          if (this.cmPage === 1) {
            this.cmList = newList
          } else {
            this.cmList = [...this.cmList, ...newList]
          }
          this.cmTotal = response.result?.total || 0
          this.cmHasMore = newList.length === this.cmPageSize
        } else {
          uni.showToast({
            title: response.message || this.$t('order_list.loadingListErr'),
            icon: 'none'
          })
        }
      } catch (error) {
        console.error(this.$t('order_list.loadingListErr'), error)
        uni.showToast({
          title: this.$t('order_list.error'),
          icon: 'none'
        })
      } finally {
        this.cmLoading = false
        uni.stopPullDownRefresh()
      }
    },

    // 中药处方：点击跳转详情
    handleCmClick(item) {
      const outpatientNo = item?.outpatient_no
      if (!outpatientNo) return
      uni.navigateTo({
        url: `/pages/medicine/detail?outpatient_no=${outpatientNo}`
      })
    },

    // 中药处方：刷新
    refreshChineseMedicineList() {
      this.cmPage = 1
      this.cmHasMore = true
      this.loadChineseMedicineList()
    },

    // 中药处方：加载更多
    async loadMoreChineseMedicine() {
      if (this.cmLoading || !this.cmHasMore) return
      this.cmPage++
      await this.loadChineseMedicineList()
    },

    // 中药处方：日期选择处理与搜索
    onCmStartChange(e) {
      this.cmSearchForm.start = e.detail.value
    },

    onCmEndChange(e) {
      this.cmSearchForm.end = e.detail.value
    },

    handleCmSearch() {
      this.cmPage = 1
      this.cmHasMore = true
      this.loadChineseMedicineList()
    },

    handleCmReset() {
      this.cmSearchForm = {
        start: '',
        end: ''
      }
      this.cmPage = 1
      this.cmHasMore = true
      this.loadChineseMedicineList()
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.hasMore = true
      this.loadOrderList()
    },

    // 重置搜索条件
    handleReset() {
      this.searchForm = {
        start: '',
        end: '',
        username: ''
      }
      this.currentPage = 1
      this.hasMore = true
      this.loadOrderList()
    },

    // 刷新列表
    refreshList() {
      this.currentPage = 1
      this.hasMore = true
      this.loadOrderList()
    },

    // 加载更多
    async loadMore() {
      if (this.loading || !this.hasMore) return

      this.currentPage++
      this.loading = true

      try {
        const cleanedSearchForm = Object.fromEntries(
          Object.entries(this.searchForm).filter(([_, v]) => v !== '')
        )
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          sortBy: this.sortBy,
          sortOrder: this.sortOrder,
          ...cleanedSearchForm
        }

        const response = await getOrderList(params)

        if (response.code === 0 || response.success) {
          const newList = response.data?.list || []
          this.orderList = [...this.orderList, ...newList]

          // 判断是否还有更多数据
          this.hasMore = newList.length === this.pageSize
        } else {
          this.currentPage-- // 恢复页码
          uni.showToast({
            title: response.message || this.t('order_list.loadingErr'),
            icon: 'none'
          })
        }
      } catch (error) {
        this.currentPage-- // 恢复页码
        console.error(this.t('order_list.loadingErr'), error)
        uni.showToast({
          title: this.t('order_list.error'),
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 排序处理
    handleSort(field) {
      if (this.sortBy === field) {
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      } else {
        this.sortBy = field
        this.sortOrder = 'desc'
      }
      this.currentPage = 1
      this.hasMore = true
      this.loadOrderList()
    },

    // 日期选择处理
    onstartChange(e) {
      this.searchForm.start = e.detail.value
    },

    onendChange(e) {
      this.searchForm.end = e.detail.value
    },

    // 订单点击处理
    handleOrderClick(order) {
      uni.navigateTo({
        url: `/pages/order/detail?outpatient_no=${order.outpatient_no}`
      })
    },

    // 格式化日期
    formatDate(dateString) {
      return formatDate(dateString)
    },



    // 计算总价
    getTotalPrice(goodInfo) {
      if (!goodInfo || !Array.isArray(goodInfo) || goodInfo.length === 0) {
        return '0.00'
      }

      const total = goodInfo.reduce((sum, item) => {
        return sum + (parseFloat(item.price) || 0)
      }, 0)

      return total.toFixed(2)
    },


  }
}
</script>

<style scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.order-list-container * {
  box-sizing: border-box;
}

/* Tab切换样式 */
.tab-section {
  background-color: #fff;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 0 20rpx;
  border-radius: 12rpx 12rpx 0 0;
}

.tab-container {
  display: flex;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 20rpx;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #007aff;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #007aff;
  border-radius: 2rpx;
}

.tab-text {
  font-size: 28rpx;
  font-weight: 500;
  color: inherit;
}

.tab-content {
  flex: 1;
}

/* 中药处方占位样式 */
.chinese-medicine-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
  background-color: #fff;
  margin: 0 20rpx 20rpx 20rpx;
  border-radius: 0 0 12rpx 12rpx;
  min-height: 400rpx;
}

.placeholder-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.placeholder-desc {
  font-size: 28rpx;
  color: #999;
}

/* 搜索区域样式 */
.search-section {
  background-color: #fff;
  padding: 30rpx 20rpx;
  margin: 0 20rpx 20rpx 20rpx;
  border-radius: 0 0 12rpx 12rpx;
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.form-item {
  display: flex;
  align-items: center;
  width: 100%;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.date-range picker {
  flex: 1;
  width: 100%;
}

.date-picker {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 18rpx 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  flex: 1;
  font-size: 28rpx;
  color: #666;
  text-align: center;
  min-height: 60rpx;
  box-sizing: border-box;
}

.separator {
  font-size: 28rpx;
  color: #999;
  padding: 0 10rpx;
  flex-shrink: 0;
}

.input {
  flex: 1;
  padding: 18rpx 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  width: 100%;
  min-height: 60rpx;
  box-sizing: border-box;
}

.search-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 15rpx;
  width: 100%;
  box-sizing: border-box;
}

.search-btn,
.reset-btn {
  flex: 1;
  padding: 12rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  height: 60rpx;
  line-height: 36rpx;
}

.search-btn {
  background-color: #007aff;
  color: #fff;
}

.reset-btn {
  background-color: #f0f0f0;
  color: #666;
}

/* 列表区域样式 */
.list-section {
  margin: 20rpx;
}

/* 订单列表样式 */
.order-list {
  background-color: #fff;
  border-radius: 12rpx;
}

.order-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  cursor: pointer;
}

.order-item:last-child {
  border-bottom: none;
}

.order-item:active {
  background-color: #f8f8f8;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-id {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.order-status {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-paid {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.status-refunded {
  background-color: #e2e3e5;
  color: #383d41;
}

.status-unknown {
  background-color: #f8f9fa;
  color: #6c757d;
}

.order-content {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.user-info {
  display: flex;
  gap: 30rpx;
}

.username {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.order-details {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.product-list {
  flex: 1;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.product-price {
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.total-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 10rpx;
  border-top: 1rpx solid #eee;
}

.total-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.amount {
  font-size: 32rpx;
  color: #ff6b35;
  font-weight: bold;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

/* 空状态和加载状态 */
.empty-state,
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
}

.empty-text,
.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载更多样式 */
.load-more-section {
  padding: 30rpx 20rpx;
  text-align: center;
}

.loading-more,
.load-more-tip,
.no-more {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin: 0 20rpx;
}

.loading-text,
.tip-text,
.no-more-text {
  font-size: 28rpx;
  color: #999;
}

.loading-text {
  color: #007aff;
}

.no-more-text {
  color: #ccc;
}
</style>
